<?php

namespace App\Http\Controllers\OgreenCard;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Service\ExcelImport;
use Maatwebsite\Excel\Facades\Excel;

class CardController extends BaseController
{

    public function types(Request $i)
    {
        $cardTypes = DB::table("og_pack as a")
            ->leftJoin("og_pack_type as b","b.pack_type_id",'=','a.pack_type')
            ->where("a.com_id",COM_ID)
            ->whereNull("a.deleted_at")
            ->select("a.*","b.pack_type_name")
            ->get();

        return self::view("card.card-type-list",['cardTypes'=>$cardTypes]);
    }

    public function typeEdit(Request $i){
        $id = (int)$i->input('id',0);

        if($i->method() == 'GET')
        {
            if($id > 0){
                $type = DB::table("og_pack")->where('pack_id',$id)->first();
            }else{
                $type = (object)self::get_empty_arr(["pack_id","pack_name","pack_price","pack_money","pack_id","pack_content","pack_type"]);
            }

            $packTypes = DB::table("og_pack_type")->get();
            return self::view("card.type-edit",['type'=>$type,'packTypes'=>$packTypes,'from'=>$i->input('from','')]);
        }

        /*POST提交*/
        $data = $i->except(["_token","id"]);
        foreach($data as $k=> $v) {
            $data[$k] = trim($v);
        }

        if(empty($data['pack_name'])) {
            return self::response('套餐名称为空');
        }

        $repeatName = DB::table('og_pack')->where('pack_name',$data['pack_name'])->where('com_id',COM_ID)->first();

        //检查名称是否存在
        if(($id <=0 && $repeatName) || ($id > 0 && $repeatName && $repeatName->pack_id !== $id)) {
            return self::response('套餐【'.$data['pack_name'].'】已存在');
        }

        //积分 套餐价值必填
        $integral = (int) $data['pack_price'];
        if($integral <=0 ) {
            return self::response('积分必须大于0');
        }

        $money = (int) $data['pack_money'];
        if($money <=0) {
            return self::response('套餐价值必须大于0');
        }


        $db = DB::table("og_pack");
        if($id > 0){
            $db->where('pack_id',$id)->update($data);
        }else{
            $data['created_at'] = self::date_time();
            $data["com_id"] = COM_ID;
            $db->insert($data);
        }

        return self::response();
    }

    public function typeDel(Request $i){
        $id = $i->input('id',0);
        if($id > 0){
            DB::table('og_pack')->where('pack_id',$id)->update(['deleted_at'=>self::date_time()]);
        }

        return self::response();
    }
    public function cards(Request $i)
    {
        $pwd    = $i->input("pwd",'');
        $code   = $i->input("code",'');
        $used   = $i->input('order',-1);
        $admin = $i->session()->get("manager");

        $db = DB::table("og_card");
        if($pwd || $code){
            $db->where(function($db) use($pwd,$code){
                if($pwd) $db->orWhere("pwd",'like',"%".$pwd."%");
                if($code)$db->orWhere('code','like',"%".$code."%");
            });
        }

        if($used == 1) $db->whereNotNull("used_at");
        if($used == 0) $db->whereNull("used_at");
        if($used == 2) $db->whereNotNull("deleted_at");
        if($used  <2){
            $db->whereNull("deleted_at");
        }

        $cards = $db->where('com_id',COM_ID)
            ->orderBy("card_id",'dest')
            ->paginate(10);
        foreach($cards as $card){
            if($admin->role == ROLE_SALE && !$card->used_at && !$card->deleted_at){
                $card->code = "";
                $card->pwd = "";
            }
        }
        $params = [
            'order' => $used,
            'code'  => $code,
            'pwd'   => $pwd
        ];

        return self::view("card.card-list",['cards'=>$cards,'params'=>$params,'admin'=>$admin]);
    }

    public function cardDel(Request $i){

        $min = $i->input('min',0);
        $max = $i->input('max',0);
        $ids = $i->input('ids','');

        if($ids) {
            $ids = explode(",",$ids);
            DB::table('og_card')->whereIn('card_id',$ids)->where('com_id',COM_ID)->delete();
        }elseif($min > 0 && $max>0){
            DB::table('og_card')
                ->where('card_id','>=',$min)
                ->where('card_id','<=',$max)
                ->where('com_id',COM_ID)
                ->whereNull('deleted_at')
                ->whereNull('used_at')
                ->delete();
        }
        return self::response();
    }

    public function cardDisable(Request $i)
    {
        $ids = explode(",",$i->input("id"));
        $note = $i->input('note');
        if(count($ids) == 0)
        {
            return self::response("请至少选中一个");
        }

        DB::table("og_card")->whereIn('card_id',$ids)->update([
            'deleted_at'=>self::date_time(),
            'note'=>$note,
            "delete_user"=>$i->session()->get("manager")->id,
        ]);
        return self::response();
    }

    public function editCard(Request $i){

    }


    public function importCardExcel(Request $i)
    {
        $cards = Excel::toArray(new ExcelImport,$i->file('excelfile'));
        $cards = $cards[0];
        array_shift($cards);
        $submit = true;
        //检查是否有效
        foreach($cards as $k=>$c){

            $res = $this->importCheck($c[0],$c[1]);
            $cards[$k][4] = $res === true ? '' : $res;
            $submit = $res === true ? $submit : false;
        }

        return self::view('card.card-import',['cards'=>$cards,'submit'=>$submit]);
    }

    private $checkCards = [];
    private function importCheck($code,$pwd){
        $code = trim($code);
        $pwd = trim($pwd);
        if($code == '' || $pwd==''){
            $res = '卡号或密码缺失';
        }elseif(in_array($code.$pwd,$this->checkCards)){
            $res = '重复';
        }elseif(DB::table("og_card")->where(['code'=>$code,'pwd'=>$pwd])->first()){
            $res = '系统已存在';
        }else{
            $res = true;
        }
        $this->checkCards[] = $code.$pwd;
        return $res;
    }


    public function importCard(Request $i){

        if($i->method() == 'GET'){
            return self::view('card.card-import',['cards'=>[],'submit'=>false]);
        }


        ## 卡号 密码 批次 类型 有效日期
        $cards = $i->input('cards');

        $validCards = [];
        $time = now()->toDateTimeString();
        foreach($cards as $key => $card)
        {
            $res = $this->importCheck($card[0],$card[1]); //检查卡号有效性
            if($res === true){
                $validCards[] = [
                    "code"  => $card[0],
                    "pwd"   => $card[1],
                    "price" => $card[2],
                    "type"  => $card[3],
                    'created_at' => $time,
                    'com_id'    => COM_ID,
                ];
            }else{
                return self::send(2001,'有不合格的卡号，请检查');
            }
        }
        $cardsArr = array_chunk($validCards,100);
        foreach($cardsArr as $c){
            DB::table("og_card")->insert($c);
        }

        return self::send(200,'导入'.count($validCards).'张卡券');
    }
    /*
     * 检查单张卡号
     * */
    public function checkCardValid(Request $i){
        $code = $i->input('code');
        $pwd = $i->input("pwd");
        if(!($code && $pwd)){
            return self::response("卡号或密码错误");
        }

        $code = strtoupper($code);
        $pwd = strtoupper($pwd);

        $card = DB::table("og_card")->where(["pwd"=>$pwd,"code"=>$code,"com_id"=>COM_ID])->first();
        if(!$card){
            return self::response("卡密错误");
        }

        if($card->used_at){
            return self::response("已使用");
        }

        if($card->deleted_at){
            return self::response("已作废");
        }

        return self::response('未使用');
    }
}
